<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Vue全栈开发美团网,">










<meta name="description" content="本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第五章，主要内容为Nuxt.js基础知识视频地址：https://coding.imooc.com/class/280.htmlNuxt.js官网：https://zh.nuxtjs.org/">
<meta name="keywords" content="Vue全栈开发美团网">
<meta property="og:type" content="article">
<meta property="og:title" content="【第五章】Vue全家桶+SSR+Koa2全栈开发美团网">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/09/16/full-stack-dev-meituan-with-vue-five/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第五章，主要内容为Nuxt.js基础知识视频地址：https://coding.imooc.com/class/280.htmlNuxt.js官网：https://zh.nuxtjs.org/">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916175825020.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917104552881.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916181718929.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916182134325.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917111130482.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917112126955.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917112941337.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917115228354.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917120240096.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917125144296.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917141245820.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917143030768.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917143747084.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917144028530.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917144924242.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917145313034.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917152129414.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916181422941.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190916181519875.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917095333725.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20190917105535617.jpg">
<meta property="og:updated_time" content="2019-09-24T00:58:53.084Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【第五章】Vue全家桶+SSR+Koa2全栈开发美团网">
<meta name="twitter:description" content="本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第五章，主要内容为Nuxt.js基础知识视频地址：https://coding.imooc.com/class/280.htmlNuxt.js官网：https://zh.nuxtjs.org/">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20190916175825020.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/09/16/full-stack-dev-meituan-with-vue-five/">





  <title>【第五章】Vue全家桶+SSR+Koa2全栈开发美团网 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/09/16/full-stack-dev-meituan-with-vue-five/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【第五章】Vue全家桶+SSR+Koa2全栈开发美团网</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-16T18:01:33+08:00">
                2019-09-16
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Vue/" itemprop="url" rel="index">
                    <span itemprop="name">Vue</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文为《Vue全家桶+SSR+Koa2全栈开发美团网》的学习笔记的第五章，主要内容为Nuxt.js基础知识<br>视频地址：<a href="https://coding.imooc.com/class/280.html" target="_blank" rel="noopener">https://coding.imooc.com/class/280.html</a><br>Nuxt.js官网：<a href="https://zh.nuxtjs.org/" target="_blank" rel="noopener">https://zh.nuxtjs.org/</a></p>
<a id="more"></a>
<h1 id="Nuxt-js概述"><a href="#Nuxt-js概述" class="headerlink" title="Nuxt.js概述"></a>Nuxt.js概述</h1><blockquote>
<p>简单的说是基于Vue2.X开发通用框架，最常用的就是用来作SSR（服务器端渲染）。<br>支持Vue Router、Vuex、Vue Server Renderer(SSR)、Vue-meta</p>
</blockquote>
<p>Why? vue开发的SPA（单页应用）不利于搜索引擎的SEO优化。</p>
<p>适用场景：Nuxt.js适合作新闻、博客、电影、咨询等需要搜索引擎提供流量的项目。</p>
<p>优点：基于 Vue.js、自动代码分层、服务端渲染、强大的路由功能，支持异步数据、<br>   静态文件服务、ES6/ES7 语法支持、打包和压缩 JS 和 CSS、HTML头部标签管理、<br>   本地开发支持热加载、集成ESLint、支持各种样式预处理器： SASS、LESS、 Stylus等</p>
<h1 id="Nuxt-js工作流"><a href="#Nuxt-js工作流" class="headerlink" title="Nuxt.js工作流"></a>Nuxt.js工作流</h1><p><img src="/blog/images/20190916175825020.jpg" alt="Nuxt.js工作流"></p>
<h1 id="Nuxt-js的安装"><a href="#Nuxt-js的安装" class="headerlink" title="Nuxt.js的安装"></a>Nuxt.js的安装</h1><p>本课程的项目是基于Koa的，所以使用如下命令安装Nuxt.js<br>参见：<a href="https://github.com/nuxt-community/koa-template" target="_blank" rel="noopener">https://github.com/nuxt-community/koa-template</a></p>
<ol>
<li>安装模板</li>
</ol>
<p><strong>注意安装前，必须要安装vue-cli脚手架，否则用不了vue进行安装，脚手架安装指令：npm install -g vue-cli</strong><br>如果没有安装vue-cli，则可能遇到如下章节的错误，解决方案见下方</p>
<p><img src="/blog/images/20190917104552881.jpg" alt="安装vue-cli"></p>
<p>安装模板的命令如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;vue init nuxt-community/koa-<span class="keyword">template</span> nuxt-learning</span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190916181718929.jpg" alt="安装模板"></p>
<ol start="2">
<li>安装项目依赖并启动项目<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//按照上图To get started里命令提示进行安装依赖和运行项目</span></span><br><span class="line"><span class="keyword">cd</span> nuxt-learning</span><br><span class="line">npm install </span><br><span class="line">npm <span class="keyword">run</span> dev</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190916182134325.jpg" alt="安装项目依赖"><br><img src="/blog/images/20190917111130482.jpg" alt="启动项目"></p>
<p>在浏览器中输入: <a href="http://localhost:3000/" target="_blank" rel="noopener">http://localhost:3000/</a> 即可启动Nuxt<br><img src="/blog/images/20190917112126955.jpg" alt="启动项目"></p>
<h1 id="Nuxt-js的使用示例"><a href="#Nuxt-js的使用示例" class="headerlink" title="Nuxt.js的使用示例"></a>Nuxt.js的使用示例</h1><h2 id="Nuxt-js的目录结构"><a href="#Nuxt-js的目录结构" class="headerlink" title="Nuxt.js的目录结构"></a>Nuxt.js的目录结构</h2><p><img src="/blog/images/20190917112941337.jpg" alt="Nuxt.js的目录结构"></p>
<h2 id="路由示例"><a href="#路由示例" class="headerlink" title="路由示例"></a>路由示例</h2><blockquote>
<p><strong>Nuxt的特点：创建即配置</strong></p>
</blockquote>
<ol>
<li>文件名即是路由<blockquote>
<p>在pages文件夹下新建一个vue文件，即可通过浏览器访问这个页面————文件名即是路由</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20190917115228354.jpg" alt="文件名即是路由"></p>
<p>Nuxt.js在背后做的两件事情：1. 自动添加search路由，并将其映射到search.vue文件；2. 将search.vue作为search路由的入口文件，可以在其中再加其他组件。</p>
<h2 id="页面模板示例"><a href="#页面模板示例" class="headerlink" title="页面模板示例"></a>页面模板示例</h2><ol>
<li><p>layouts：存放页面模板，如定义公共组件</p>
<figure class="highlight dts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//页面模板</span></span><br><span class="line"><span class="params">&lt;template&gt;</span></span><br><span class="line">  <span class="params">&lt;div&gt;</span></span><br><span class="line">    <span class="params">&lt;nuxt/&gt;</span>    <span class="comment">//路由的入口页面，完全类似于router-view标签</span></span><br><span class="line">    <span class="params">&lt;my-footer/&gt;</span>  <span class="comment">//components中的公共组件</span></span><br><span class="line">  <span class="params">&lt;/div&gt;</span></span><br><span class="line"><span class="params">&lt;/template&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>components: 存放具体的公共组件</p>
</li>
</ol>
<p><img src="/blog/images/20190917120240096.jpg" alt="页面模板"></p>
<ol start="3">
<li><p>自定义页面模板</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">//layout/search.vue</span><br><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"layout-search"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Search layout header<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">nuxt</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">footer</span>&gt;</span>Search layout footer<span class="tag">&lt;/<span class="name">footer</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="css">  <span class="selector-class">.layout-search</span>&#123;</span></span><br><span class="line"><span class="css">    <span class="selector-tag">color</span><span class="selector-pseudo">:red</span>;</span></span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>使用自定义模板</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">//pages/search.vue</span><br><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"page"</span>&gt;</span></span><br><span class="line">     Page is search</span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">  <span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"><span class="actionscript">  	<span class="comment">//使用search.vue页面模板</span></span></span><br><span class="line"><span class="actionscript">    layout: <span class="string">'search'</span></span></span><br><span class="line">  &#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>使用自定义页面模板的路由显示效果如下：</p>
<p><img src="/blog/images/20190917125144296.jpg" alt="自定义页面模板"></p>
<h2 id="异步数据示例"><a href="#异步数据示例" class="headerlink" title="异步数据示例"></a>异步数据示例</h2><ol>
<li><p>创建Server端数据接口</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//server/interface/city.js</span></span><br><span class="line"><span class="keyword">import</span> Router from <span class="string">'koa-router'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//路由的前缀</span></span><br><span class="line"><span class="keyword">const</span> router = <span class="keyword">new</span> Router(&#123;</span><br><span class="line">  prefix: <span class="string">'/city'</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">router.<span class="keyword">get</span>(<span class="string">'/list'</span>, <span class="keyword">async</span> (ctx) =&gt;&#123;</span><br><span class="line">  ctx.body = &#123;</span><br><span class="line">    list:[<span class="string">'北京'</span>,<span class="string">'天津'</span>]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> router</span><br></pre></td></tr></table></figure>
</li>
<li><p>Server端入口文件注册这个组件</p>
<figure class="highlight n1ql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">//server/<span class="keyword">index</span>.js</span><br><span class="line">import cityInterface <span class="keyword">from</span> <span class="string">'./interface/city.js'</span></span><br><span class="line"></span><br><span class="line">async <span class="keyword">function</span> <span class="keyword">start</span> () &#123;</span><br><span class="line"></span><br><span class="line">	//... 添加如下这一句代码</span><br><span class="line">    app.<span class="keyword">use</span>(cityInterface.routes()).<span class="keyword">use</span>(cityInterface.allowedMethods())</span><br><span class="line">	</span><br><span class="line">	app.<span class="keyword">use</span>(ctx =&gt; &#123;</span><br><span class="line">    ctx.status = <span class="number">200</span></span><br><span class="line">    ctx.respond = <span class="literal">false</span> // Mark request <span class="keyword">as</span> handled <span class="keyword">for</span> Koa</span><br><span class="line">    ctx.req.ctx = ctx // This might be useful later <span class="keyword">on</span>, <span class="built_in">e</span>.g. <span class="keyword">in</span> nuxtServerInit <span class="keyword">or</span> <span class="keyword">with</span> nuxt-stash</span><br><span class="line">    nuxt.render(ctx.req, ctx.res)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>通过浏览器访问服务端数据接口<br>在浏览器中输入：<a href="http://localhost:3000/city/list，即可看到如下数据" target="_blank" rel="noopener">http://localhost:3000/city/list，即可看到如下数据</a><br><img src="/blog/images/20190917141245820.jpg" alt="通过浏览器访问接口"></p>
</li>
</ol>
<ol start="4">
<li>前端访问服务端数据接口(使用axios的写法)<figure class="highlight django"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml">//pages/search.vue</span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"page"</span>&gt;</span></span></span><br><span class="line"><span class="xml">     Page is search</span></span><br><span class="line"><span class="xml">     <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">"(item,idx) in list"</span> <span class="attr">:key</span>=<span class="string">'idx'</span>&gt;</span></span><span class="template-variable">&#123;&#123;item&#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span></span><br><span class="line"><span class="xml">     <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="xml">  import axios from 'axios'</span></span><br><span class="line"><span class="xml">  export default &#123;</span></span><br><span class="line"><span class="xml">    layout: 'search',</span></span><br><span class="line"><span class="xml">    data() &#123;</span></span><br><span class="line"><span class="xml">      return &#123;</span></span><br><span class="line"><span class="xml">        list: []</span></span><br><span class="line"><span class="xml">      &#125;</span></span><br><span class="line"><span class="xml">    &#125;,</span></span><br><span class="line"><span class="xml">    async mounted() &#123;</span></span><br><span class="line"><span class="xml">      let self = this</span></span><br><span class="line"><span class="xml">      let &#123;status, data: &#123;list&#125;&#125; = await axios.get('/city/list')</span></span><br><span class="line"><span class="xml">      if (status === 200) &#123;</span></span><br><span class="line"><span class="xml">        self.list = list</span></span><br><span class="line"><span class="xml">      &#125;</span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">  &#125;</span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190917143030768.jpg" alt="使用axios的访问接口"></p>
<blockquote>
<p>此方式的特点：mounted()过程不在服务器端执行，是在客户端执行，类似于ajax(查看源代码看不到数据)</p>
</blockquote>
<ol start="5">
<li>前端访问服务端数据接口(使用nuxt的写法)<figure class="highlight django"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"page"</span>&gt;</span></span></span><br><span class="line"><span class="xml">     Page is search</span></span><br><span class="line"><span class="xml">     <span class="tag">&lt;<span class="name">ul</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">"(item,idx) in list"</span> <span class="attr">:key</span>=<span class="string">'idx'</span>&gt;</span></span><span class="template-variable">&#123;&#123;item&#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span></span><br><span class="line"><span class="xml">     <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span></span><br><span class="line"><span class="xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span></span><br><span class="line"><span class="xml">  import axios from 'axios'</span></span><br><span class="line"><span class="xml">  export default &#123;</span></span><br><span class="line"><span class="xml">    layout: 'search',</span></span><br><span class="line"><span class="xml">    data() &#123;</span></span><br><span class="line"><span class="xml">      return &#123;</span></span><br><span class="line"><span class="xml">        list: []</span></span><br><span class="line"><span class="xml">      &#125;</span></span><br><span class="line"><span class="xml">    &#125;,</span></span><br><span class="line"><span class="xml">    //asyncData()主要用来处理组件的数据；</span></span><br><span class="line"><span class="xml">    //fetch()主要用来处理vuex相关的数据；</span></span><br><span class="line"><span class="xml">    async asyncData() &#123;</span></span><br><span class="line"><span class="xml">      let &#123;status, data: &#123;list&#125;&#125; = await axios.get('http://localhost:3000/city/list')</span></span><br><span class="line"><span class="xml">      if (status === 200) &#123;</span></span><br><span class="line"><span class="xml">        return &#123;</span></span><br><span class="line"><span class="xml">          list  //赋值给data中的list</span></span><br><span class="line"><span class="xml">        &#125;</span></span><br><span class="line"><span class="xml">      &#125;</span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">  &#125;</span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190917143747084.jpg" alt="使用nuxt的访问接口"></p>
<blockquote>
<p>此方式的特点：asyncData()过程在服务器端执行，数据随模板返回到客户端(查看源代码可以看到数据)</p>
</blockquote>
<p><img src="/blog/images/20190917144028530.jpg" alt="查看源代码"></p>
<h2 id="SSR剖析"><a href="#SSR剖析" class="headerlink" title="SSR剖析"></a>SSR剖析</h2><ol>
<li>如何将数据与模板在服务端渲染————见上节中的asyncData()过程</li>
<li>如何将数据同步给浏览器端<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">通过在<span class="keyword">script</span>标签中window.__NUXT__对象</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20190917144924242.jpg" alt="SSR剖析"></p>
<h2 id="Vuex在Nuxt中的应用示例"><a href="#Vuex在Nuxt中的应用示例" class="headerlink" title="Vuex在Nuxt中的应用示例"></a>Vuex在Nuxt中的应用示例</h2><p><strong>Nuxt的特点：创建即配置</strong><br>详情见官网：<a href="https://zh.nuxtjs.org/guide/vuex-store/" target="_blank" rel="noopener">https://zh.nuxtjs.org/guide/vuex-store/</a><br><img src="/blog/images/20190917145313034.jpg" alt="官网说明"></p>
<ol>
<li>创建store目录和vuex组件<br><img src="/blog/images/20190917152129414.jpg" alt="官网说明"></li>
</ol>
<p><strong>注意：创建store目录和vuex组件完成之后，需要重启项目，否则可能在前端页面中访问Vuex组件时报错：$store not found</strong></p>
<ol start="2">
<li>在前端页面中访问vuex组件<figure class="highlight django"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml">//pages/search.vue</span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">ul</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">li</span> <span class="attr">v-for</span>=<span class="string">"(item,idx) in $store.state.city.list"</span> <span class="attr">:key</span>=<span class="string">'idx'</span>&gt;</span></span><span class="template-variable">&#123;&#123;item&#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">li</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<h1 id="Nuxt总结"><a href="#Nuxt总结" class="headerlink" title="Nuxt总结"></a>Nuxt总结</h1><ol>
<li>components： 定义复用组件</li>
<li>layouts： 定义复用页面结构</li>
<li>pages： 创建路由</li>
<li>store： 管理vuex</li>
<li>ssr： 使用asyncData()或fetch()</li>
<li>nuxtServerInit: <a href="https://zh.nuxtjs.org/examples/auth-routes/#nuxtserverinit-%E6%96%B9%E6%B3%95" target="_blank" rel="noopener">https://zh.nuxtjs.org/examples/auth-routes/#nuxtserverinit-%E6%96%B9%E6%B3%95</a></li>
</ol>
<h1 id="Vue-SSR工作原理"><a href="#Vue-SSR工作原理" class="headerlink" title="Vue SSR工作原理"></a>Vue SSR工作原理</h1><ol>
<li>SSR作用: 解决SEO问题；解决内容快速展示的问题；</li>
<li>SSR实现原理： 在服务端异步请求数据、并和模板组合到一起进行页面渲染，再采用同步方式返回到客户端</li>
<li>为什么服务端的数据还要同步到客户端： 因为客户端需要使用数据和模板来编译虚拟DOM，来与服务端对比编译结果，如果不一致则客户端重新请求数据；如果一致客户端才会给对应的DOM注册事件</li>
</ol>
<h1 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h1><h2 id="Command-vue-init-requires-a-global-addon-to-be-installed"><a href="#Command-vue-init-requires-a-global-addon-to-be-installed" class="headerlink" title="Command vue init requires a global addon to be installed."></a>Command vue init requires a global addon to be installed.</h2><blockquote>
<p>Command vue init requires a global addon to be installed.<br>Please run yarn global add @vue/cli-init and try again.</p>
</blockquote>
<p><img src="/blog/images/20190916181422941.jpg" alt="Command vue init requires a global addon to be installed"></p>
<p>错误原因：vue init 需要全局安装vue/cli-init<br>解决办法：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">npm</span> <span class="selector-tag">install</span> <span class="selector-tag">-g</span> @<span class="keyword">vue</span>/<span class="keyword">cli</span>-<span class="keyword">init</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190916181519875.jpg" alt="全局安装vue/cli-init"></p>
<h2 id="Plugin-Preset-files-are-not-allowed-to-export-objects-only-functions"><a href="#Plugin-Preset-files-are-not-allowed-to-export-objects-only-functions" class="headerlink" title="Plugin/Preset files are not allowed to export objects, only functions"></a>Plugin/Preset files are not allowed to export objects, only functions</h2><blockquote>
<p>参考自：<a href="https://blog.csdn.net/Umbrella_Um/article/details/98700893" target="_blank" rel="noopener">https://blog.csdn.net/Umbrella_Um/article/details/98700893</a></p>
</blockquote>
<p>错误描述：输入npm run dev启动Nuxt.js时，报如下错误：<br><img src="/blog/images/20190917095333725.jpg" alt="输入npm run dev启动Nuxt.js时报错"></p>
<p>错误原因：版本依赖升级导致的编译失败问题</p>
<p>解决办法：执行这两个命令, 最后在重新启动项目就可以解决了</p>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm un backpack-core eslint eslint-loader</span><br><span class="line">npm i backpack-core@<span class="number">0.8</span><span class="number">.3</span> eslint@<span class="number">3.19</span><span class="number">.0</span> eslint-loader@<span class="number">2.1</span><span class="number">.1</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20190917105535617.jpg" alt="输入npm run dev启动Nuxt.js时报错的解决办法"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Vue全栈开发美团网/" rel="tag"># Vue全栈开发美团网</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/09/12/full-stack-dev-meituan-with-vue-four/" rel="next" title="【第四章】Vue全家桶+SSR+Koa2全栈开发美团网">
                <i class="fa fa-chevron-left"></i> 【第四章】Vue全家桶+SSR+Koa2全栈开发美团网
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/09/17/full-stack-dev-meituan-with-vue-six/" rel="prev" title="【第六章】Vue全家桶+SSR+Koa2全栈开发美团网">
                【第六章】Vue全家桶+SSR+Koa2全栈开发美团网 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Nuxt-js概述"><span class="nav-number">1.</span> <span class="nav-text">Nuxt.js概述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Nuxt-js工作流"><span class="nav-number">2.</span> <span class="nav-text">Nuxt.js工作流</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Nuxt-js的安装"><span class="nav-number">3.</span> <span class="nav-text">Nuxt.js的安装</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Nuxt-js的使用示例"><span class="nav-number">4.</span> <span class="nav-text">Nuxt.js的使用示例</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Nuxt-js的目录结构"><span class="nav-number">4.1.</span> <span class="nav-text">Nuxt.js的目录结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#路由示例"><span class="nav-number">4.2.</span> <span class="nav-text">路由示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#页面模板示例"><span class="nav-number">4.3.</span> <span class="nav-text">页面模板示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步数据示例"><span class="nav-number">4.4.</span> <span class="nav-text">异步数据示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SSR剖析"><span class="nav-number">4.5.</span> <span class="nav-text">SSR剖析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Vuex在Nuxt中的应用示例"><span class="nav-number">4.6.</span> <span class="nav-text">Vuex在Nuxt中的应用示例</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Nuxt总结"><span class="nav-number">5.</span> <span class="nav-text">Nuxt总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Vue-SSR工作原理"><span class="nav-number">6.</span> <span class="nav-text">Vue SSR工作原理</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#常见错误"><span class="nav-number">7.</span> <span class="nav-text">常见错误</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Command-vue-init-requires-a-global-addon-to-be-installed"><span class="nav-number">7.1.</span> <span class="nav-text">Command vue init requires a global addon to be installed.</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Plugin-Preset-files-are-not-allowed-to-export-objects-only-functions"><span class="nav-number">7.2.</span> <span class="nav-text">Plugin/Preset files are not allowed to export objects, only functions</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
